package io.wdb.wxapp.controller;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wdb.exchange.constant.EventEnum;
import com.wdb.exchange.constant.SourceEnum;
import com.wdb.exchange.model.Event;
import com.wdb.exchange.model.RespModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.wdb.common.exception.RspCodeEnum;
import io.wdb.common.utils.CommonUtil;
import io.wdb.common.utils.DateUtils;
import io.wdb.common.utils.R;
import io.wdb.config.AmqpConfig;
import io.wdb.handler.AmqpSendHandler;
import io.wdb.handler.ApiServiceHandler;
import io.wdb.modules.activity.wxapp.entity.HdActivityEntity;
import io.wdb.modules.activity.wxapp.entity.HdCardAttenderEntity;
import io.wdb.modules.activity.wxapp.entity.HdCardInitiatorEntity;
import io.wdb.modules.activity.wxapp.entity.HdShareRecordEntity;
import io.wdb.modules.activity.wxapp.entity.HdUserEntity;
import io.wdb.modules.activity.wxapp.service.HdActivityService;
import io.wdb.modules.activity.wxapp.service.HdCardAttenderService;
import io.wdb.modules.activity.wxapp.service.HdCardInitiatorService;
import io.wdb.modules.activity.wxapp.service.HdShareRecordService;
import io.wdb.modules.activity.wxapp.service.HdUserService;
import io.wdb.wxapp.model.HdCardAttenderModel;
import io.wdb.wxapp.model.HdCardInitiatorModel;

@Controller
@RequestMapping("card")
@Api(tags="B.cardActivity api" ) 
public class CardActivityController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(CardActivityController.class);
	
	@Autowired
	private HdCardInitiatorService hdCardInitiatorService;
	
	@Autowired
	private HdShareRecordService hdShareRecordService;
	
	@Autowired
	private HdCardAttenderService hdCardAttenderService;
	
	@Autowired
	private HdUserService hdUserService;
	
	@Autowired
	private HdActivityService hdActivityService;
	
	@Autowired
	private ApiServiceHandler apiServiceHandler;
	
	@Autowired
	private AmqpSendHandler amqpSendHandler;
	
	//发起者初始分享
	@RequestMapping(value="cardShareInitiator",method = RequestMethod.POST)
	@ApiOperation(value="月卡活动发起者分享", notes="发起者分享成功后，根据hdUserId/activityId添加一条Initiator")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userId",value = "userId", dataType = "Long", paramType = "query", required=true),
		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "usertoken",value = "usertoken", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "activityId",value = "活动id", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "path",value = "分享路径", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "wxGroupId",value = "分享的群名/个人", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "title",value = "title", dataType = "String", paramType = "query", required=false)

	})
	@ResponseBody
	public R cardShareInitiator(HttpServletRequest request) {
		String activityId = request.getParameter("activityId");
		String useridStr = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");

		
		//分享信息
		String path = request.getParameter("path");
		String title = request.getParameter("title");
		String wxGroupId = request.getParameter("wxGroupId");
		
		checkIsNull(activityId, "activityId");
		checkIsNull(usertoken, "usertoken");
		if(!isEmpty(useridStr)) {
			checkIsNull(mobile, "mobile");
		}

		HdUserEntity userEntity =  hdUserService.getUserinfoByUsertoken(null, appid, useridStr, usertoken, mobile);
		if(isEmpty(userEntity) || isEmpty(userEntity.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		String hdUserId = userEntity.getId();
		//存储初始化数据
		HdCardInitiatorEntity entity = new HdCardInitiatorEntity();
		entity.setActivityId(activityId);
		entity.setUserId(hdUserId);
		
		HdCardInitiatorEntity initiator = hdCardInitiatorService.save(entity);
		
		Map<String, Object> result = new HashMap<>();
		result.put("initiator", HdCardInitiatorModel.convert(initiator));
		
		//如果分享存在wxGroupId，存储
		if(!ObjectUtils.isEmpty(wxGroupId)) {
			checkIsNull(path, "path");
			checkIsNull(wxGroupId, "wxGroupId");
			checkIsNull(title, "title");
			//存储分享信息
			HdShareRecordEntity hdShareRecord = new HdShareRecordEntity();
			hdShareRecord.setPath(path);
			hdShareRecord.setShareTime(new Date());
			hdShareRecord.setTitle(title);
			hdShareRecord.setWxGroupId(wxGroupId);
			hdShareRecord.setUserId(hdUserId);
			hdShareRecord.setActivityId(activityId);
			hdShareRecordService.save(hdShareRecord);
		}		
		
		return R.ok(result);
	}
	//分享用户获得月卡占比
	@RequestMapping(value="getCardActivityCurrentInfo",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="发起者查看月卡活动进度信息", notes="根据hdUserId和activityid获得分析者信息",response=HdCardInitiatorModel.class)
	@ApiImplicitParams({
		@ApiImplicitParam(name = "userid",value = "发起者userid", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "usertoken",value = "发起者usertoken", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "activityId",value = "活动Id", dataType = "String", paramType = "query", required=true)
	})
	public R getCardActivityCurrentInfo(HttpServletRequest request) {
		String activityId = request.getParameter("activityId");
		String userid = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		String mobile = request.getParameter("mobile");

		checkIsNull(activityId, "activityId");
		checkIsNull(userid, "userid");
		checkIsNull(usertoken, "usertoken");
		checkIsNull(mobile, "mobile");
		
		HdUserEntity userIdEntity = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		if(isEmpty(userIdEntity)) {
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		String hdUserId  = userIdEntity.getId();
		//返回结果
		Map<String, Object> result = new HashMap<>();
		//根据hdPid和activityId查询pid用户活动信息
		Map<String, Object> hdCardInitMap = new HashMap<>();
		hdCardInitMap.put("userId", hdUserId);
		hdCardInitMap.put("activityId", activityId);
		List<Map<String, Object>> initiators = null;
		List<HdCardInitiatorEntity> hdCardInitiatorList = hdCardInitiatorService.queryList(hdCardInitMap);
		if(hdCardInitiatorList != null && hdCardInitiatorList.size() > 0) {
			initiators = new ArrayList<>();
			for(HdCardInitiatorEntity hdCardInitiator:hdCardInitiatorList) {
				Map<String, Object> initiator = new HashMap<>();
				initiator.put("initiateTime", DateUtils.getDatePoor(new Date(),hdCardInitiator.getInitiateTime()));//发起时间
				if(hdCardInitiator.getFinishRate() > 10000 ) {
					initiator.put("finishRate",  100);
				}else {
					initiator.put("finishRate",  hdCardInitiator.getFinishRate()/100);
				}
				initiator.put("hdCardInitiatorId", hdCardInitiator.getId());
				Map<String, Object> hdCardAttenderMap = new HashMap<>();
				
				hdCardAttenderMap.put("cardInitiatorId", hdCardInitiator.getId());
				List<HdCardAttenderEntity> hdCardAttenderEntities = hdCardAttenderService.queryList(hdCardAttenderMap);
				if(hdCardAttenderEntities.isEmpty()) {
					initiator.put("friendsCount", 0);//好友助力数
				}else {
					initiator.put("friendsCount", hdCardAttenderEntities.size());
				}
				initiator.put("status", 0);
				if (hdCardInitiator.getStatus() == 1 && hdCardInitiator.getAccount() == 1) {
					initiator.put("status", hdCardInitiator.getStatus());//进度达到100%且发放成功再展示已完成
					RespModel respModel = apiServiceHandler.userVIPEndDate(userIdEntity.getMobile());
					if(respModel != null && respModel.getCode() == 0) {
						initiator.put("endTime", respModel.getDetails().get("end_date"));
					}else {
						logger.info("userIdEntity.getMobile()[{}] userVIPEndDate error [{}]", userIdEntity.getMobile(), respModel.getDetails().get("end_date"));
					}
					
				}
				initiators.add(initiator);
			}
			
		}
		
		result.put("initiators", initiators);

		return R.ok(result);
	}
	//排行榜数据
	//活动开始/截止时间
	@RequestMapping(value="getParentCardInfo",method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据initorId获得分享者信息", notes="根据initorId获得分享者信息,返回currentAttender是否为null展示按钮")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "initorId",value = "发起活动id,创建活动成功返回的", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "usertoken",value = "usertoken", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "userid",value = "userid", dataType = "String", paramType = "query", required=false),
		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query", required=false)

	})
	public R getParentCardInfo(HttpServletRequest request) {
		//发起活动id
		String initorId = request.getParameter("initorId");
		String usertoken = request.getParameter("usertoken");
		String userid = request.getParameter("userid");
		String mobile = request.getParameter("mobile");
		checkIsNull(initorId, "initorId");
		String appid = request.getHeader("appid");
		checkIsNull(appid, "appid");
		checkIsNull(usertoken, "usertoken");
		if(!isEmpty(userid)) {
			checkIsNull(mobile, "mobile");
		}

		HdUserEntity requestUserinfo = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		if(isEmpty(requestUserinfo) || isEmpty(requestUserinfo.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		String openid = requestUserinfo.getWxOpenid();
		
		//点击分享出去的数据统计
		try {
			Event event = new Event();
			event.userId = requestUserinfo.getApiUserId();
			event.source = SourceEnum.ACTIVITY;
			event.event = EventEnum.FISSION_VIEW;
			event.openId = openid;
			event.appId = appid;
			event.mobile = requestUserinfo.getMobile();
			event.eventTime = new Date().getTime();
			//数据统计
			amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
		} catch (Exception e) {
			logger.info("异步数据统计error:{}",e.getMessage());
			e.printStackTrace();
		}
		
		
		//返回结果
		Map<String, Object> result = new HashMap<>();
		HdCardInitiatorEntity hdCardInitiator = hdCardInitiatorService.queryObject(initorId);
		Map<String, Object> initiator = new HashMap<>();

		if(hdCardInitiator.getFinishRate() > 10000 ) {
			initiator.put("finishRate",  100);
		}else {
			initiator.put("finishRate",  hdCardInitiator.getFinishRate()/100);
		}
		//获取用户信息
		HdUserEntity userEntity = hdUserService.queryObject(hdCardInitiator.getUserId());
		initiator.put("avatar", userEntity.getAvatar());//头像
		initiator.put("nickName",userEntity.getNickname());//昵称
		
		//活动时间
		HdActivityEntity activityEntity = hdActivityService.queryObject(hdCardInitiator.getActivityId());
		initiator.put("startTime", activityEntity.getStartTime());
		initiator.put("endTime", activityEntity.getEndTime());
		initiator.put("activityName", activityEntity.getName());
		initiator.put("activityId", hdCardInitiator.getActivityId());
		//当前活动信息
		result.put("initiator", initiator);
		
		result.put("content", activityEntity.getContent());
		
		//TODO 获取当前参与者排行榜
		Map<String, Object> hdCardAttenderMap = new HashMap<>();
		hdCardAttenderMap.put("cardInitiatorId", initorId);
		hdCardAttenderMap.put("sidx", "score");
		hdCardAttenderMap.put("order", "desc");

		List<HdCardAttenderEntity> attenderEntities = hdCardAttenderService.queryList(hdCardAttenderMap);
		result.put("attendors", HdCardAttenderModel.convert(attenderEntities,hdUserService));
		
		//TODO 当前用户是否有参与
		//根据appid和openid查询hdUserId
		HdCardAttenderModel currentAttender = null;
		if((!ObjectUtils.isEmpty(appid)) && (!ObjectUtils.isEmpty(openid))) {
			Map<String, Object> activityUserInfoMap = new HashMap<>();
			activityUserInfoMap.put("wxAppid", appid);
			activityUserInfoMap.put("wxOpenid", openid);
			
			List<HdUserEntity> userEntities = hdUserService.queryList(activityUserInfoMap);
			if(userEntities != null && userEntities.size() > 0) {
				HdUserEntity userInfo = userEntities.get(0);
				Map<String, Object> attendorMap = new HashMap<>();
				attendorMap.put("userId", userInfo.getId());//hdUserId
				List<HdCardAttenderEntity> attenders =  hdCardAttenderService.queryList(attendorMap);
				if (attenders != null && attenders.size() >= Integer.valueOf(getConfig("cardActivityAtendersTimes"))) {
					currentAttender = HdCardAttenderModel.convert(attenders.get(0),hdUserService);
				}
				//TODO 查询给当前用户支援次数
				attendorMap.put("cardInitiatorId", initorId);//cardInitiatorId
				attenders = hdCardAttenderService.queryList(attendorMap);
				if (attenders != null && attenders.size() > 0) {
					currentAttender = HdCardAttenderModel.convert(attenders.get(0),hdUserService);
				}
				
			}
		}else {
			logger.info("cannot get current user openid and appid");
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(),"cannot get current user openid and appid");
		}
		
		result.put("currentAttender", currentAttender);
		return R.ok(result);
	}
	
	//保存支持者的分数/助力占比
	@RequestMapping(value="saveAttendorInfo",method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value="根据initorId保存支持者信息", notes="根据initorId保存支持者信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "initorId",value = "发起活动id,创建活动成功返回的", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "score",value = "点击分数", dataType = "int", paramType = "query", required=true),
		@ApiImplicitParam(name = "userid",value = "userid", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "usertoken",value = "usertoken", dataType = "String", paramType = "query", required=true),
		@ApiImplicitParam(name = "mobile",value = "mobile", dataType = "String", paramType = "query", required=false)
	})
	public synchronized R saveAttendorInfo(HttpServletRequest request) {
		String cardInitiatorId = request.getParameter("initorId");
		String score = request.getParameter("score");
		String mobile = request.getParameter("mobile");
		String userid = request.getParameter("userid");
		String usertoken = request.getParameter("usertoken");
		
		HdUserEntity userinfoApi = hdUserService.getUserinfoByUsertoken(null, appid, userid, usertoken, mobile);
		if(isEmpty(userinfoApi) || isEmpty(userinfoApi.getSessionKey())) {//如果返回为空，表示usertoken过期
			return R.error(RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspCode(), RspCodeEnum.USER_TOKEN_IS_UNVALID.getRspMsg());
		}
		String hdUserId = userinfoApi.getId();
		
		logger.info("cardInitiatorId:{},hdUserId:{},score:{},mobile:{}",cardInitiatorId,hdUserId,score,mobile);
		checkIsNull(cardInitiatorId, "initorId");
		checkIsNull(hdUserId, "hdUserId");
		checkIsNull(score, "score");
		//===========异步数据统计FISSION_LOTTERY START===========//
		try {
			Event event = new Event();
			event.userId = userinfoApi.getApiUserId();
			event.source = SourceEnum.ACTIVITY;
			event.event = EventEnum.FISSION_LOTTERY;
			event.openId = userinfoApi.getWxOpenid();
			event.appId = appid;
			event.mobile = userinfoApi.getMobile();
			event.eventTime = new Date().getTime();
			//数据统计
			amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
		} catch (Exception e) {
			logger.info("异步数据统计error:{}",e.getMessage());
			e.printStackTrace();
		}
		//===========异步数据统计FISSION_LOTTERY END===========//
		//保存（）
		HdCardAttenderEntity hdCardAttender = new HdCardAttenderEntity();
		hdCardAttender.setCardInitiatorId(cardInitiatorId);
		hdCardAttender.setUserId(hdUserId);
		hdCardAttender.setScore(Integer.valueOf(score));
		hdCardAttender.setStartTime(new Date());
		hdCardAttender.setAccount(0);//发放记录
		
		if(ObjectUtils.isEmpty(mobile)) {
			HdUserEntity userEntity = hdUserService.queryObject(hdCardAttender.getUserId());
			mobile = userEntity.getMobile();
		}
		
		Map<String, Object> hdCardAttenderMap = new HashMap<>();
		hdCardAttenderMap.put("userId", hdCardAttender.getUserId());
		List<HdCardAttenderEntity> hdCardAttenderEntities = hdCardAttenderService.queryList(hdCardAttenderMap);
		if(hdCardAttenderEntities != null && hdCardAttenderEntities.size() >= Integer.valueOf(getConfig("cardActivityAtendersTimes"))) {
			return R.error(RspCodeEnum.CARD_ACTIVITY_ENOUGH.getRspCode(), RspCodeEnum.CARD_ACTIVITY_ENOUGH.getRspMsg());
		}
		
		
		hdCardAttenderMap.put("cardInitiatorId", hdCardAttender.getCardInitiatorId());
		 hdCardAttenderEntities = hdCardAttenderService.queryList(hdCardAttenderMap);
		if(hdCardAttenderEntities != null && hdCardAttenderEntities.size() > 0) {
			//如果已经存在记录提示不能再提交
			HdCardAttenderEntity exitCardAttender = hdCardAttenderEntities.get(0);
			if(exitCardAttender.getAccount() != 0 ) {
				return R.error(RspCodeEnum.ATTENDOR_IS_EXIT.getRspCode(), RspCodeEnum.ATTENDOR_IS_EXIT.getRspMsg());
			} else if(!ObjectUtils.isEmpty(mobile)) {
				RespModel respModel = apiServiceHandler.presentAmount(exitCardAttender.getMoney(), mobile);
				if(respModel != null && respModel.getCode() == 0) {
					exitCardAttender.setAccount(1);
					//===========异步数据统计FISSION_PRESENT START===========//
					try {
						Event event = new Event();
						event.userId = userinfoApi.getApiUserId();
						event.source = SourceEnum.ACTIVITY;
						event.event = EventEnum.FISSION_PRESENT;
						event.openId = userinfoApi.getWxOpenid();
						event.appId = appid;
						event.mobile = userinfoApi.getMobile();
						event.eventTime = new Date().getTime();
						//数据统计
						amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
					} catch (Exception e) {
						logger.info("异步数据统计error:{}",e.getMessage());
						e.printStackTrace();
					}
					//===========异步数据统计FISSION_PRESENT END===========//
				}else {
					logger.info("presentAmount model[{}] respModel error :[{}] ", mobile, respModel);
				}
				hdCardAttenderService.update(exitCardAttender);
				return R.ok();
			} else {
				checkIsNull(mobile, "mobile");//发放奖励给参与者必须要手机号
				return R.ok();
			}
			
		}else {
			
			try {
				Event event = new Event();
				event.userId = userinfoApi.getApiUserId();
				event.source = SourceEnum.ACTIVITY;
				event.event = EventEnum.FISSION_LOTTERY;
				event.openId = userinfoApi.getWxOpenid();
				event.appId = appid;
				event.mobile = userinfoApi.getMobile();
				event.eventTime = new Date().getTime();
				//数据统计
				amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
			} catch (Exception e) {
				logger.info("异步数据统计error:{}",e.getMessage());
				e.printStackTrace();
			}

			int totalScore = Integer.valueOf(getConfig("cardActivityTotalScore"));//TODO 总分数从数据库config中获取
			int finishRate = hdCardAttender.getScore()*10000/totalScore;
			int sendMoney = Integer.valueOf(score) * Integer.valueOf(getConfig("cardActivityPerScore"));
			
			//发放money
			
			HdCardInitiatorEntity initiatorEntity = new HdCardInitiatorEntity();
			initiatorEntity.setId(cardInitiatorId);
			initiatorEntity.setTotalScore(Integer.valueOf(score));
			initiatorEntity.setFinishRate(finishRate);//TODO 计算totalScore 750
			
			if(sendMoney > 0 && hdCardAttender.getAccount() != 1 && !CommonUtil.isEmpty(mobile) 
					&& !CommonUtil.isEmpty(userinfoApi.getMobile())) {//没有获取钱
				RespModel respModel = apiServiceHandler.presentAmount(sendMoney, userinfoApi.getMobile());
				if(respModel != null && respModel.getCode() == 0) {
					hdCardAttender.setAccount(1);
					//===========异步数据统计FISSION_PRESENT START===========//
					try {
						Event event = new Event();
						event.userId = userinfoApi.getApiUserId();
						event.source = SourceEnum.ACTIVITY;
						event.event = EventEnum.FISSION_PRESENT;
						event.openId = userinfoApi.getWxOpenid();
						event.appId = appid;
						event.mobile = userinfoApi.getMobile();
						event.eventTime = new Date().getTime();
						//数据统计
						amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
					} catch (Exception e) {
						logger.info("异步数据统计error:{}",e.getMessage());
						e.printStackTrace();
					}
					//===========异步数据统计FISSION_PRESENT END===========//
				}else {
					logger.info("hdCardAttender[{}]moble[{}]presentAmount error: [{}]",hdCardAttender.getId(),userinfoApi.getMobile(), respModel);
				}
			}
			
			hdCardAttender.setMoney(sendMoney);
			hdCardAttenderService.save(hdCardAttender);
			
			
			HdCardInitiatorEntity hdCardInitiator = hdCardInitiatorService.queryObject(cardInitiatorId);
			
			logger.info("get month card percent:mobile,{},{},hdUserId:{}",mobile,hdCardInitiator.getFinishRate() + initiatorEntity.getFinishRate(),hdUserId);
			//概率100% 发放月卡
			if ((hdCardInitiator.getFinishRate() + initiatorEntity.getFinishRate()) >= 10000
					&& hdCardInitiator.getAccount() != 1) {
				// 发月卡的手机号 根据hdCardInitiator userId查询
				HdUserEntity vipUser = hdUserService.queryObject(hdCardInitiator.getUserId());
				initiatorEntity.setStatus(1);
				RespModel respModel = apiServiceHandler.presentVIP(vipUser.getMobile(), 1, 0);
				if(respModel != null && respModel.getCode() == 0) {
					initiatorEntity.setAccount(1);
					//===========异步数据统计FISSION_CARD_SUCCESS START===========//
					try {
						Event event = new Event();
						event.userId = userinfoApi.getApiUserId();
						event.source = SourceEnum.ACTIVITY;
						event.event = EventEnum.FISSION_CARD_SUCCESS;
						event.appId = appid;
						event.mobile = vipUser.getMobile();
						event.eventTime = new Date().getTime();
						//数据统计
						amqpSendHandler.sendFanout(AmqpConfig.SERVICE_EXCHANGE, event.toJson());
					} catch (Exception e) {
						logger.info("异步数据统计error:{}",e.getMessage());
						e.printStackTrace();
					}
					//===========异步数据统计FISSION_CARD_SUCCESS END===========//
				}else {
					logger.info("hdCardInitiatorId[{}] hdCardInitiator presentVIP error[{}]",hdCardInitiator.getId(),respModel);
				}
			}
			hdCardInitiatorService.update(initiatorEntity);
			return R.ok();
		}
		
	}
	
}
